package com.insight.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.insight.common.util.oConvertUtils;
import com.insight.modules.system.entity.SysDepartPermission;
import com.insight.modules.system.entity.SysDepartRole;
import com.insight.modules.system.entity.SysDepartRolePermission;
import com.insight.modules.system.entity.SysPermissionDataRule;
import com.insight.modules.system.mapper.SysDepartPermissionMapper;
import com.insight.modules.system.mapper.SysDepartRoleMapper;
import com.insight.modules.system.mapper.SysDepartRolePermissionMapper;
import com.insight.modules.system.mapper.SysPermissionDataRuleMapper;
import com.insight.modules.system.service.ISysDepartPermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 部门权限表
 * @Author: jeecg-boot
 * @Date:   2020-02-11
 * @Version: V1.0
 */
@Service
public class SysDepartPermissionServiceImpl extends ServiceImpl<SysDepartPermissionMapper, SysDepartPermission> implements ISysDepartPermissionService {
    @Resource
    private SysPermissionDataRuleMapper ruleMapper;

    @Resource
    private SysDepartRoleMapper sysDepartRoleMapper;

    @Resource
    private SysDepartRolePermissionMapper departRolePermissionMapper;

    /**
     * 保存部门权限
     * @param departId 部门ID
     * @param permissionIds 当前权限ID字符串，逗号分隔
     * @param lastPermissionIds 之前权限ID字符串，逗号分隔
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDepartPermission(String departId, String permissionIds, String lastPermissionIds) {
        // 计算需要新增的权限ID集合（lastPermissionIds中没有，permissionIds中有）
        List<String> add = getDiff(lastPermissionIds, permissionIds);
        if(add != null && add.size() > 0) {
            List<SysDepartPermission> list = new ArrayList<>();
            for (String p : add) {
                if(oConvertUtils.isNotEmpty(p)) {
                    // 构建部门权限实体对象
                    SysDepartPermission rolepms = new SysDepartPermission(departId, p);
                    list.add(rolepms);
                }
            }
            // 批量保存新增的部门权限
            this.saveBatch(list);
        }

        // 计算需要删除的权限ID集合（permissionIds中没有，lastPermissionIds中有）
        List<String> delete = getDiff(permissionIds, lastPermissionIds);
        if(delete != null && delete.size() > 0) {
            for (String permissionId : delete) {
                // 删除部门权限表中对应记录
                this.remove(new QueryWrapper<SysDepartPermission>().lambda()
                        .eq(SysDepartPermission::getDepartId, departId)
                        .eq(SysDepartPermission::getPermissionId, permissionId));

                // 查询该部门所有角色
                List<SysDepartRole> sysDepartRoleList = sysDepartRoleMapper.selectList(
                        new LambdaQueryWrapper<SysDepartRole>().eq(SysDepartRole::getDepartId, departId));
                List<String> roleIds = sysDepartRoleList.stream()
                        .map(SysDepartRole::getId)
                        .collect(Collectors.toList());

                // 如果部门角色存在，删除部门角色权限中对应的权限
                if(roleIds != null && roleIds.size() > 0){
                    departRolePermissionMapper.delete(new LambdaQueryWrapper<SysDepartRolePermission>()
                            .eq(SysDepartRolePermission::getPermissionId, permissionId));
                }
            }
        }
    }

    /**
     * 根据部门ID和权限ID，查询关联的数据权限规则列表
     * @param departId 部门ID
     * @param permissionId 权限ID
     * @return 数据权限规则列表
     */
    @Override
    public List<SysPermissionDataRule> getPermRuleListByDeptIdAndPermId(String departId, String permissionId) {
        // 查询部门权限关系对象
        SysDepartPermission departPermission = this.getOne(new QueryWrapper<SysDepartPermission>().lambda()
                .eq(SysDepartPermission::getDepartId, departId)
                .eq(SysDepartPermission::getPermissionId, permissionId));
        if(departPermission != null){
            LambdaQueryWrapper<SysPermissionDataRule> query = new LambdaQueryWrapper<>();
            // 按逗号分割规则ID字符串查询
            query.in(SysPermissionDataRule::getId, Arrays.asList(departPermission.getDataRuleIds().split(",")));
            // 按创建时间倒序排序
            query.orderByDesc(SysPermissionDataRule::getCreateTime);
            // 返回查询结果
            return this.ruleMapper.selectList(query);
        } else {
            return null;
        }
    }

    /**
     * 计算差异集合：找出diff中有，但main中没有的元素
     * @param main 基准字符串，逗号分隔
     * @param diff 对比字符串，逗号分隔
     * @return 差异列表
     */
    private List<String> getDiff(String main, String diff){
        if(oConvertUtils.isEmpty(diff)) {
            return null;
        }
        if(oConvertUtils.isEmpty(main)) {
            return Arrays.asList(diff.split(","));
        }

        // 将main字符串拆分成数组
        String[] mainArr = main.split(",");
        // 将diff字符串拆分成数组
        String[] diffArr = diff.split(",");

        // 使用map存储main中的元素，方便快速判断
        Map<String, Integer> map = new HashMap<>();
        for (String string : mainArr) {
            map.put(string, 1);
        }

        List<String> res = new ArrayList<>();
        // 遍历diff数组，筛选出不在main中的元素
        for (String key : diffArr) {
            if(oConvertUtils.isNotEmpty(key) && !map.containsKey(key)) {
                res.add(key);
            }
        }
        return res;
    }
}

